/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package sopraim.presenter.services.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.collections.ListUtils;
import sopraim.entity.TextMessage;
import sopraim.entity.User;
import sopraim.model.Model;
import sopraim.presenter.services.UserService;

/**
 *
 * @author Juste Abel
 */
public class Utils {

    public void sendMail(User user, String link){
        String to[] = {user.getMail()};
        String from = "sopraim@gmail.com";
        String subject = "Your SopraIM account has been created";
        String message =  "<html> "+
        "<body style='font-size:large;'>"+
        "<div style='font-size:large;'>"+
                                "<h3>Welcome to SopraIM, the Sopra Group instant messaging system</h3>"+
                                "Your login : "+
                                "<span style='color:grey;'>"+user.getUsername()+"</span><br>"+
                                "Your password : "+
                                "<span style='color:grey;'>"+user.getPassword()+"</span>"+
                                "<br>"+
                                "Connection page :<a href='"+link+"'> Sopra Instant Messaging</a><br>"+
                                "<p>Please change your password as soon as you get connected.<br>"+
                                "Feel free to get in touch with the administrators whenever you want to customize your profile"+
                                " or report a bug."+
                                "</p>"+
                                "Enjoy!"+
                                "<br>"+
                                "<span style='color:grey;'>SopraIM team</span>"+
                                "</div>"+
                             "</body>"+
                         "</html>";
        try {
            postMail(to, subject, message, from);
        } catch (MessagingException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    UserService userSevice = new UserService();
    
    public JsonArray toJson(ArrayList<User>list){
        if(list.isEmpty() || list==null){
            return Json.createArrayBuilder().build();
            
        }
        JsonArrayBuilder builder = Json.createArrayBuilder();
        for(User u :list){
            JsonObject j = Json.createObjectBuilder()
                    .add("id", u.getId())
                    .add("username", u.getUsername())
                    .add("firstname", u.getFirstName()!=null?u.getFirstName():"")
                    .add("lastname", u.getName()!=null?u.getName():"")
                    .add("location", u.getLocation()!=null?u.getLocation().getName():"")
                    .add("status", u.getStatus()!=null?u.getStatus().getName():"")
                    .add("isAdmin", u.getIsAdmin())
                    .build();
            builder.add(j);
            
        }
        return builder.build();
        
    }
    public JsonArray messageToJson(ArrayList<TextMessage>list){
        if(list.isEmpty() || list==null){
            return Json.createArrayBuilder().build();
            
        }
        JsonArrayBuilder builder = Json.createArrayBuilder();
        for(TextMessage m :list){
            JsonObject j = Json.createObjectBuilder()
                    .add("from", m.getSender()!=null?m.getSender().getUsername():"")
                    .add("message", m.getMessage()!=null?m.getMessage():"")
                    .build();
            builder.add(j);
            
        }
        return builder.build();
        
    }
    public JsonObject toJson(User u){
        return Json.createObjectBuilder()
                .add("id", u.getId())
                .add("username", u.getUsername())
                .add("firstname", u.getFirstName()!=null?u.getFirstName():"")
                .add("lastname", u.getName()!=null?u.getName():"")
                .add("location", u.getLocation()!=null?u.getLocation().getName():"")
                .add("status", u.getStatus()!=null?u.getStatus().getName():"")
                .add("isAdmin", u.getIsAdmin())
                .build();
    }
    
    public void toTextFile(User localUser, File path){
        try {
            //convert to xml, pdf, or text
            FileWriter writer =new FileWriter(path, false);
            ArrayList<User> friends = userSevice.getFriends(localUser);
            for(User u : friends){
                ArrayList<TextMessage> sent = userSevice.getAllMessageSendTo(localUser,u);
                ArrayList<TextMessage> received = userSevice.getAllMessageReceivedFrom(localUser, u);
                ArrayList<TextMessage> list = (ArrayList<TextMessage>) ListUtils.union(sent, received);
                Collections.sort(list);
                
                writer.append("Conversation with "+u.getFirstName()+" "+u.getName()+" Pseudo :"+u.getUsername()+"\n\n\n");
                for(TextMessage m : list){
                    try {
                        String messageType="Message", message = m.getMessage();
                        if(m.getMessage().startsWith("{_file_}")){
                            messageType = "File";
                            message = m.getMessage().substring(8);
                        }
                        else if(m.getMessage().startsWith("{_link_}")){
                            messageType = "Link";
                            message = m.getMessage().substring(8);
                        }
                        String toPrint = m.getDate()+":"+"from "+
                                m.getSender().getUsername()+":\n"+
                                messageType+" : "+message;
                        writer.append(toPrint+"\n\n");
                    } catch (IOException ex) {
                        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                writer.append("\n\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
    {
        boolean debug = false;
        
        //Set the host smtp address
        Properties properties = new Properties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.user", "sopraim"); // User name
        properties.put("mail.smtp.password", "sopra2013"); // password
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");
        String host = "smtp.gmail.com";
        properties.setProperty("mail.smtp.host", host);
        
        SmtpAuthenticator authentication = new SmtpAuthenticator();
        javax.mail.Message msg = new MimeMessage(Session
                .getInstance(properties, authentication));
        // create a message
        
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++)
        {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        
        
        // Optional : You can also set your custom headers in the Email if you Want
        msg.addHeader("MyHeaderName", "myHeaderValue");
        
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/html; charset=utf-8");
        Transport.send(msg);
    }
    String result;
    
    public class SmtpAuthenticator extends Authenticator {
        public SmtpAuthenticator() {
            
            super();
        }
        
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = "sopraim";
            String password = "sopra2013";
            if ((username != null) && (username.length() > 0) && (password != null)
                    && (password.length   () > 0)) {
                
                return new PasswordAuthentication(username, password);
            }
            
            return null;
        }
    }
   
}
